package cn.hn.tx.mail.app;

import java.util.Date;
import java.util.List;

import cn.hn.comm.Tools;
import cn.hn.comm.mail.MailSendResult;
import cn.hn.comm.mail.SimpleMailSender;
import cn.hn.tx.mail.model.MailAccount;
import cn.hn.tx.mail.model.MailAddress;
import cn.hn.tx.mail.model.MailContent;
import cn.hn.tx.mail.service.IMailService;

public class MailSender implements Runnable {

	private String status = "待发送！";

	private int sendedMailAccount;
	private MailContent mailContent;
	private List<MailAccount> mailAccounts;
	private List<MailAddress> mailAddresses;
	private int index_MailAccount;
	private int index_MailAddress;

	private int state = STATE_READY;
	final public static int STATE_SENDING = 0;
	final public static int STATE_READY = 1;

	private Thread thread;

	private IMailService mailService;

	private boolean sendFlag;

	// 同一个邮件账号发送邮件间隔时间
	private int mailTimeInterval;
	// 邮件发送时间间隔随机数
	private int randIntervalExt;

	private int sendMailTimeInterval;

	private long sleepStartTime;

	public void sendTestMail() {
		mailContent = mailService
				.queryOldestMailContentByStatus(MailContent.STATE_NO_PUBLISH);
		SimpleMailSender.SendHtmlMail("tianxin007.gnway.net", "sh",
				"tongyongMM", "yuannana2006@126.com", "sh@tianxin.com",
				mailContent.getTitle(), mailContent.getContent());
	}

	public void sendTestMail(String host, String username, String password,
			String toaddress, String fromaddress) {
		mailContent = mailService
				.queryOldestMailContentByStatus(MailContent.STATE_NO_PUBLISH);
		SimpleMailSender.SendHtmlMail(host, username,
				password, toaddress, fromaddress,
				mailContent.getTitle(), mailContent.getContent());
	}

	public void sendMail() {
		if (state == STATE_READY) {
			sendFlag = true;
			state = STATE_SENDING;
			status = "正在发送...";
			mailContent = mailService
					.queryOldestMailContentByStatus(MailContent.STATE_NO_PUBLISH);
			if (mailContent != null) {
				mailAccounts = mailService
						.queryAllMailAccountByStatus(MailAccount.STATE_ENABLE);
				mailAddresses = mailService
						.queryAllMailAddressByStatus(MailAddress.STATE_ENABLE);

				sendMailTimeInterval = mailTimeInterval / mailAccounts.size();

				if (thread == null) {
					thread = new Thread(this);
				}
				thread.start();
				System.out.println(status);
			} else {
				status = "无邮件可发！";
				state = STATE_READY;
			}
		}
	}

	public void stopSendMail() {

		if (sendFlag) {
			status = "正在停止邮件发送服务！";
			sendFlag = false;
		} else {
			status = "待发送！";
		}
		System.out.println(status);
		// state = STATE_READY;
	}

	private void sendMailOver() {
		sendFlag = false;
		sendedMailAccount = 0;
		index_MailAccount = 0;
		index_MailAddress = 0;
		mailContent = null;
		status = "待发送！";
		thread = null;
		state = STATE_READY;
	}

	private MailAccount getMailAccount() {
		index_MailAccount++;
		if (index_MailAccount >= mailAccounts.size()) {
			index_MailAccount = 0;
		}
		return mailAccounts.get(index_MailAccount);
	}

	public void run() {
		long lStart;
		long lEnd;
		long lDiff;

		int iMailInterval;

		if (mailContent != null) {
			mailContent.setPublish_time(Tools.getCurDate(null));
			mailContent.setStatus(MailContent.STATE_YES_PUBLISH);
			mailService.updateMailContent(mailContent);

			for (int i = 0; i < mailAddresses.size(); i++) {
				if (!sendFlag) {
					break;
				}

				iMailInterval = sendMailTimeInterval * 1000
						+ Tools.getRandomInt(0, randIntervalExt * 1000);

				lStart = System.currentTimeMillis();
				index_MailAddress = i;
				MailAddress mailAddress = mailAddresses.get(i);
				MailAccount mailAccount = getMailAccount();
				status += "...正在使用" + mailAccount.getHost() + ":"
						+ mailAccount.getUserName() + ",向"
						+ mailAddress.getMail_address() + "发送邮件。" + "<br/>"
						+ "   已经发送邮件:" + i + "    总共邮件：" + mailAddresses.size();
				System.out.println(status);
				try {
					MailSendResult msr = SimpleMailSender.SendHtmlMail(
							mailAccount.getHost(), mailAccount.getUserName(),
							mailAccount.getPassword(), mailAddress
									.getMail_address(), mailAccount
									.getFromaddress(), mailContent.getTitle()
									+ "_" + System.currentTimeMillis(),
							mailContent.getContent() + "<br/>"
									+ System.currentTimeMillis());

					if (msr.getState() == msr.STATE_SUC) {
						mailAddress.setSuc_num(mailAddress.getSuc_num() + 1);
						mailAddress.setLast_suc_time(new Date());
					} else {
						mailAddress.setFail_num(mailAddress.getFail_num() + 1);
						mailAddress.setLast_fail_info(msr.getInfo());
						mailAddress.setLast_fail_time(new Date());
					}
					mailAddress.setLast_send_time(new Date());

					mailService.updateMailAddress(mailAddress);

					lEnd = System.currentTimeMillis();

					lDiff = lEnd - lStart;
					if (lDiff < iMailInterval) {
						try {
							status = "已使用" + mailAccount.getHost() + ":"
									+ mailAccount.getUserName() + ",向"
									+ mailAddress.getMail_address()
									+ "发送邮件,发送结果:" + msr.getInfo() + "。正在休眠"
									+ (iMailInterval - lDiff) + "<br/>"
									+ "   已经发送邮件:" + i + "    总共邮件："
									+ mailAddresses.size();
							System.out.println(status);
							// System.out.println("发送间隔:" + iMailInterval +
							// ",正在休眠"
							// + (iMailInterval - lDiff));
							sleepStartTime = System.currentTimeMillis();
							thread.sleep(iMailInterval - lDiff);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				} catch (Exception e) {

				}

			}// end for()
		}
		sendMailOver();

	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public int getSendedMailAccount() {
		return sendedMailAccount;
	}

	public void setSendedMailAccount(int sendedMailAccount) {
		this.sendedMailAccount = sendedMailAccount;
	}

	public MailContent getMailContent() {
		return mailContent;
	}

	public void setMailContent(MailContent mailContent) {
		this.mailContent = mailContent;
	}

	public List<MailAccount> getMailAccounts() {
		return mailAccounts;
	}

	public void setMailAccounts(List<MailAccount> mailAccounts) {
		this.mailAccounts = mailAccounts;
	}

	public List<MailAddress> getMailAddresses() {
		return mailAddresses;
	}

	public void setMailAddresses(List<MailAddress> mailAddresses) {
		this.mailAddresses = mailAddresses;
	}

	public int getIndex_MailAccount() {
		return index_MailAccount;
	}

	public void setIndex_MailAccount(int index_MailAccount) {
		this.index_MailAccount = index_MailAccount;
	}

	public int getIndex_MailAddress() {
		return index_MailAddress;
	}

	public void setIndex_MailAddress(int index_MailAddress) {
		this.index_MailAddress = index_MailAddress;
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public IMailService getMailService() {
		return mailService;
	}

	public void setMailService(IMailService mailService) {
		this.mailService = mailService;
	}

	public boolean isSendFlag() {
		return sendFlag;
	}

	public void setSendFlag(boolean sendFlag) {
		this.sendFlag = sendFlag;
	}

	public int getMailTimeInterval() {
		return mailTimeInterval;
	}

	public void setMailTimeInterval(int mailTimeInterval) {
		this.mailTimeInterval = mailTimeInterval;
	}

	public int getRandIntervalExt() {
		return randIntervalExt;
	}

	public void setRandIntervalExt(int randIntervalExt) {
		this.randIntervalExt = randIntervalExt;
	}

	public long getSleepStartTime() {
		return sleepStartTime;
	}

	public void setSleepStartTime(long sleepStartTime) {
		this.sleepStartTime = sleepStartTime;
	}

}
